#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 23:05:43 2013

@author: Casa
"""

from traits.api import HasTraits,Enum,File,Str,Button,List,Instance,Bool
from traitsui.api import View,Item,Group,ListEditor,HGroup
from testset import testset
from FDR import FDR
from OSHC import OSHC
from VSHC import VSHC
from WHT import WHT
from time import clock
import TEST
import cPickle
import os

class ui_testset(HasTraits):
    filename=File
    choose=Bool(True)
    view=View(HGroup(Item('filename'),
                     Item('choose',show_label=False)))
    #def _filename_changed(self):
        #self.ts=testset(self.filename)5
    
class TestCompression(HasTraits):
    WHT=Bool
    ALL_TEST=Bool
    coding=Enum(['FDR','OSHC','VSHC'])
    tslist=List(Instance(ui_testset,factory=ui_testset))
    content=Str
    Run=Button
    status=Str('Liang Zhang,HNU,lag.zhang@gmail.com')
    view=View(
        Group(
        Item('tslist',editor=ListEditor(style='custom',use_notebook=True),show_label=False),
        label='Testset',show_border=True),
        Item('content',show_label=False,style='custom'),
        HGroup('coding','WHT','ALL_TEST',Item('Run',show_label=False)),
        Item('status',show_label=False,style='readonly'),
        title='TestDataCompression',width=420,height=500,resizable=True
        )
    
    def _Run_fired(self): 
        self.content=''
        #for all test
        self.status='ALL_TEST'
        if self.ALL_TEST:            
            TEST.ALL_TEST(self.tslist)
            return
        #wht+coding
        if self.coding=='FDR':
            coding=FDR
        elif self.coding=='OSHC':
            coding=OSHC
        elif self.coding=='VSHC':
            coding=VSHC
        self.status=self.coding;
        if self.WHT: self.status+='|WHT';
        sum=0.0; 
        num=0
        #every test set
        start=clock()
        for ui_ts in self.tslist:
            if not ui_ts.choose:continue
            ts=testset(ui_ts.filename)
            self.content+=ts.name
            data=ts.data;
            if self.WHT:
                data=WHT(data)
            size=coding(data)
            ratio=1-size*1.0/data.size;
            sum+=ratio
            num+=1
            self.content+=str('\t%.2f\n'%(ratio*100))
            print ts.name,ratio
        end=clock()
        self.status+='|'+str('%.0fms'%((end-start)*1000))
        self.content+=str('---\nAverage:\t%.2f\n'%(sum/num*100))
        
if __name__=="__main__":
    if os.path.exists('tc.pkl'):
        with open('tc.pkl','rb') as f:
            tc=cPickle.load(f)
    else:
        tc=TestCompression()
    tc.configure_traits()
    with open('tc.pkl','wb') as f:
            cPickle.dump(tc,f)
